/**************旅游攻略路由器***************************/
const express = require('express')
const pool = require('../pool.js')
const router = express.Router()
module.exports = router

//1.添加一个查询所有攻略的路由器
//GET /show
//请求地址:http://127.0.0.1:8080/v1/method/show
router.get('/show',(req,res)=>{
	let sql = 'select title,deliver_time,detail from method'
	pool.query(sql,(err,result)=>{
		if(err) throw err
		res.send(result)
	})
})

//2.添加一个查询指定数量攻略的路由器
//GET /list
//请求参数:pageSize=5
//请求地址:http://127.0.0.1:8080/v1/method/list?pageSize=5
router.get('/list',(req,res)=>{
	let ps = req.query.pageSize
	ps = ps?parseInt(ps):5
	let sql = 'select title,deliver_time,detail from method limit ?'
	pool.query(sql,ps,(err,result)=>{
		if(err) throw err 
		res.send(result)
	})
})

//3.新增攻略的路由器
//POST /add
//请求主体:title=xxx&deliver_time=xxx&detail=xxx
//响应消息{code:200,msg:'添加成功'}
//请求地址:http://127.0.0.1:8080/v1/method/add
router.post('/add',(req,res)=>{
	let tit = req.body.title
	let time = req.body.deliver_time
	let detail = req.body.detail
	
	if(!tit){
		res.send({code:201,msg:'标题不能为空'})
		return
	}
	if(!detail){
		res.send({code:201,msg:'内容不能为空'})
		return
	}
	let sql = 'insert into method(title,deliver_time,detail) values(?,?,?)'
	pool.query(sql,[tit,time,detail],(err,result)=>{
		if(err) throw err
		res.send({code:200,msg:'添加成功'})
	})
})

//4.删除一个攻略的接口
//DELETE /del
//请求参数:/:method_id
//响应消息:{code:200,msg:'删除成功'}{code:201,msg:'删除失败'}
//请求地址:http://127.0.0.1:8080/v1/method/del/6
router.delete('/del/:method_id',(req,res)=>{
	let id = req.params.method_id
	id = parseInt(id)
	let sql = 'delete from method where method_id=?'
	pool.query(sql,id,(err,result)=>{
		if(err) throw err
		if(result.affectedRows>0){
			res.send({code:200,msg:'删除成功'})
		}else{
			res.send({code:201,msg:'删除失败'})
		}
	})
})